package com.mp.approvalreq.servlet;

import com.alibaba.fastjson.JSONObject;
import com.mp.approvalreq.entity.Template;
import com.mp.approvalreq.service.ReadTemplateServicePrx;
import com.mp.approvalreq.util.ServiceUtils;
import com.mp.user.entity.User;
import com.plusmoney.exception.RpcServerLogicalException;
import com.plusmoney.util.Utils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 获得用过的公司模板
 *
 * @author Administrator
 */
@WebServlet("/getTemplateUsed")
public class GetTemplateUsed extends AbstractServlet {

	private static final Logger logger = LoggerFactory.getLogger(GetTemplateUsed.class);
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		try {
			User user = getReqUser(req);
			
			String reqBody = getContent(req);
			logger.info("json参数 {}", reqBody);

			changeUser(user, reqBody);

			ReadTemplateServicePrx readTemplateServicePrx = ServiceUtils.getReadTemplateServicePrx();
			List<Template> templates = readTemplateServicePrx.getTemplateUsed(user);
			
			returnResult(resp, templates);
		} catch (Throwable e) {
			onThrowable(req, resp, e);
		}
	}
	
	private void returnResult(HttpServletResponse resp, List<Template> templates) throws IOException {
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("result", "0");
		jsonObject.put("res_info", "获得成功");
		jsonObject.put("item", templates);
		
		logger.info(jsonObject.toJSONString());
		
		printJson(resp, jsonObject.toJSONString());
	}
	
	private User changeUser(User user, String reqBody) {
		if (StringUtils.isNotEmpty(reqBody)) {
			User bodyUser = getUser(reqBody);
			checkUser(user);
			bodyUser.setCompanyId(user.getCompanyId());
		}
		return user;
	}
	
	private User getUser(String reqBody) {
		User user = null;
		try {
			user = JSONObject.parseObject(reqBody, User.class);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new RpcServerLogicalException(1, "客户端参数错误");
		}
		return user;
	}
	
	protected void checkUser(User user) {
		if (Utils.isNull(user.getContactId())) {
			throw new RpcServerLogicalException(1, "参数错误");
		}
	}
}
